// action - state management
import { jwt } from '@/utils/index'
import * as actionTypes from './actions'
import { DefaultAvatar } from '@/store/constant'

interface TokenInfo {
  name: string
  user_id: string
  timestamp: string
  isValid: boolean
}

export interface User {
  tokenInfo: TokenInfo
  token: string
  avatarUrl: string
}

export const initialState = {
  tokenInfo: jwt(localStorage.getItem('token') ?? ''),
  token: localStorage.getItem('token') ?? '',
  avatarUrl: localStorage.getItem('avatarUrl') || DefaultAvatar
}

// ==============================|| CUSTOMIZATION REDUCER ||============================== //
interface Action {
  type: any
  token: string
  avatarUrl: string
}

const userReducer = (state = initialState, action: Action) => {
  switch (action.type) {
    case actionTypes.SET_TOKEN:
      return {
        ...state,
        token: action.token,
        tokenInfo: jwt(action.token)
      }
    case actionTypes.SET_AVATAR:
      localStorage.setItem('avatarUrl', action.avatarUrl)
      return {
        ...state,
        avatarUrl: action.avatarUrl
      }
    default:
      return state
  }
}

export default userReducer
